require('./goods.css');
import * as ajax from './ajax';
$.init();

// 点击购物车
$('.bottom .join-cart').click(function () {
    let gid = $(this).data('gid');
    showSelectPanel();
});


$('#buy-now').click(function () {
    let input = $('.num input');
    let id = input.data('gid');
    let curNum = parseInt(input.val());
    ajax.changeGoodNum(id, curNum + 1, (res) => {
        if (res.rel == 1) {
            window.location.href = _cartIndex;
        } else {
            $.toast(res.msg);
        }
    });

});


//已选择商品关闭按钮
$('.good-select-panel .close').click(function () {
    hideSelectPanel();
});


//添加商品数量
$('.good-page .add').click(function (e) {
    let input = $(this).siblings('input');
    let id = input.data('gid');
    let curNum = parseInt(input.val());
    ajax.changeGoodNum(id, curNum + 1, (res) => {
        if (res.rel == 1) {
            input.val(res.goodnum);
            $('.cart-num').text(res.cartgoodsnum);
            input.attr('data-cid', res.cart_id);
        } else {
            $.toast(res.msg);
        }
    });
});

//减少商品数量
$('.good-page .subtract').click(function (e) {
    let input = $(this).siblings('input');
    let id = input.data('gid');
    let cart_id = input.data('cid');
    let curNum = parseInt(input.val());
    if (curNum > 1) {
        ajax.changeGoodNum(id, curNum - 1, (res) => {
            if (res.rel == 1) {
                input.val(res.goodnum);
                $('.cart-num').text(res.cartgoodsnum);
            } else {
                $.toast(res.msg);
            }
        });
    } else {
        if (cart_id != "") {
            ajax.delGood(cart_id, id, (res) => {
                if (res.rel == 1) {
                    input.val(0);
                    input.attr('data-cid', "");
                } else {
                    $.toast(res.msg);
                }
            });
        }
    }
});


//隐藏已选商品信息
const hideSelectPanel = () => {
    $('.mask').remove();
    $('.good-select-panel').removeClass('show');
};


//显示已选商品信息
const showSelectPanel = () => {
    $('.content').append('<div class="mask"></div>');
    $('.good-select-panel').addClass('show');
};



